package com.ease.common.util;

import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

import com.ease.model.type.DateDay;

public abstract class DateUtil extends Detect {

	public static DateDay getDay(Date date) {
		Calendar calendar = Calendar.getInstance(TimeZone.getDefault());
		calendar.setTime(date);
		return DateDay.get((short) calendar.get(Calendar.DAY_OF_WEEK));
	}

	public static int getDayOfMonth(Date date) {
		Calendar calendar = Calendar.getInstance(TimeZone.getDefault());
		calendar.setTime(date);
		return calendar.get(Calendar.DAY_OF_MONTH);
	}

	/**
	 * 获取月份，1-12月
	 * 
	 * @param date
	 * @return
	 */
	public static int getMonth(Date date) {
		Calendar calendar = Calendar.getInstance(TimeZone.getDefault());
		calendar.setTime(date);
		return calendar.get(Calendar.MONTH) + 1;
	}

	/**
	 * 获取19xx,20xx形式的年
	 * 
	 * @param date
	 * @return
	 */
	public static int getYear(Date date) {
		Calendar calendar = Calendar.getInstance(TimeZone.getDefault());
		calendar.setTime(date);
		return calendar.get(Calendar.YEAR);
	}

	public static int getHourOfDay(Date date) {
		Calendar calendar = Calendar.getInstance(TimeZone.getDefault());
		calendar.setTime(date);

		return calendar.get(Calendar.HOUR_OF_DAY);
	}

	// TODO bug Date date =  getLastDurationDate("2013-06-01 13:00:00", 60) still "2013-06-01 13:00:00";
	public static Date getLastDurationDate(Date date, int duration) {
		Calendar c = Calendar.getInstance(TimeZone.getDefault());
		c.setTime(date);
		int minute = c.get(Calendar.MINUTE);
		minute = (int) (minute / duration) * duration;

		Calendar calendar = Calendar.getInstance(TimeZone.getDefault());
		calendar.set(c.get(Calendar.YEAR), c.get(Calendar.MONTH) + 1, c.get(Calendar.DAY_OF_MONTH), c.get(Calendar.HOUR_OF_DAY), minute, 0);
		return calendar.getTime();
	}

	public static Date getLastQuarterDate(Date date) {
		return getLastDurationDate(date, 15);
	}

	public static Date getLastHalfHourDate(Date date) {
		return getLastDurationDate(date, 30);
	}

	public static void main(String[] args) {
		Date date = new Date();// 2013-05-28 17:46:32

		System.out.println(DateFormatUtil.toDatetimeString(date));
		date = getLastHalfHourDate(date);// 2013-06-28 17:30:00
		System.out.println(DateFormatUtil.toDatetimeString(date));
	}

}
